package com.roger.myHome.service.impl;


import com.roger.myHome.domain.TbFinancial;
import com.roger.myHome.entity.dto.FinancialAddReq;
import com.roger.myHome.entity.dto.RedemptionDto;
import com.roger.myHome.entity.qto.FinancialQry;
import com.roger.myHome.entity.vo.FinancialDetailVo;
import com.roger.myHome.entity.vo.FinancialIncomeVo;
import com.roger.myHome.entity.vo.FinancialVo;
import com.roger.myHome.exception.MyParseException;
import com.roger.myHome.mapper.FinancialMapper;
import com.roger.myHome.page.EUDataGridResult;
import com.roger.myHome.service.FinancialService;
import com.roger.myHome.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class FinancialServiceImpl implements FinancialService {

    @Resource
    private FinancialMapper financialMapper;

    private final static BigDecimal HUNDRED = new BigDecimal("100");

    private static BigDecimal ONE_YEAR = new BigDecimal("365");

    static {
        int year = DateUtil.currentYear();
        boolean res = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ? true : false;
        if (res) {
            ONE_YEAR = new BigDecimal("366");
        }
    }

    @Override
    public EUDataGridResult page(FinancialQry financialQry) {
        List<FinancialVo> list = financialMapper.page(financialQry);

        Long total = financialMapper.total(financialQry);

        return new EUDataGridResult(list , total);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public String add(FinancialAddReq financialAddReq) {
        TbFinancial tbFinancial = new TbFinancial();
        Map<String, String> hashMap = new HashMap<String, String>();
        BeanUtils.copyProperties(financialAddReq, tbFinancial);
        tbFinancial.setCreateTime(new Date());
        tbFinancial.setId(SystemUtil.getId());
        financialMapper.insert(tbFinancial);

        hashMap.put("result", "新增成功!");

        return StringUtils.getJSONString(hashMap);
    }

    /**
     * 赎回
     * @param redemptionDto
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public String redemption(RedemptionDto redemptionDto) {
        //UpdateWrapper<TbFinancial> updateWrapper = new UpdateWrapper<>();
        Map<String, String> hashMap = new HashMap<String, String>();
        String state = "已购买";
        if ("赎回".equals(redemptionDto.getOpType())) {
            state = "已赎回";
        }
        try {
            TbFinancial vo = financialMapper.selectById(redemptionDto.getId());
            BigDecimal buyMoney = vo.getBuyMoney();
            String buyDate = vo.getBuyDate();
            Long keepDays = DateUtil.getDiffDays(redemptionDto.getRedemptionDate(),buyDate);
            TbFinancial obj = new TbFinancial();
            obj.setId(redemptionDto.getId());
            obj.setIncome(redemptionDto.getIncome());
            obj.setRedemptionDate(redemptionDto.getRedemptionDate());
            obj.setState(state);
            obj.setKeepDays(Integer.valueOf(keepDays.toString()));
//            updateWrapper.set("income",redemptionDto.getIncome()).set("redemption_date",redemptionDto.getRedemptionDate())
//                    .set("state",state).set("keep_days", keepDays).eq("id",redemptionDto.getId());
//
//            financialMapper.update(null, updateWrapper);
            BigDecimal profit =
                    redemptionDto.getIncome().subtract(buyMoney).divide(new BigDecimal(keepDays),2, BigDecimal.ROUND_HALF_UP);
            obj.setProfit(profit);


            financialMapper.updateById(obj);

            hashMap.put("result", "赎回成功!");
        } catch (ParseException e) {
            throw new MyParseException("赎回失败,解析日期错误!");
        }
        return StringUtils.getJSONString(hashMap);
    }

    @Override
    public String searchTotalIncome() {
        Map<String, String> hashMap = new HashMap<String, String>();
        FinancialIncomeVo financialIncomeVo = financialMapper.searchTotalIncome();
        StringBuffer sb = new StringBuffer("总投资:");
        BigDecimal totalInvestment = financialIncomeVo.getTotalInvestment();
        BigDecimal totalIncome = financialIncomeVo.getTotalIncome();

        BigDecimal sumProfit = financialMapper.findSumProfit();

        BigDecimal yearProfit = sumProfit.multiply(ONE_YEAR);

        sb.append(totalInvestment)
                .append("元,共收益:").append(totalIncome)
                .append("元,每天收入:").append(sumProfit).append("元,预计年收入:").append(yearProfit).append("元");
        hashMap.put("result", sb.toString());
        return StringUtils.getJSONString(hashMap);
    }

    @Override
    public String checkIncome(Long id){
        Map<String, String> hashMap = new HashMap<String, String>();
        TbFinancial tbFinancial = financialMapper.selectById(id);

        BigDecimal resultIncome = tbFinancial.getIncome().subtract(tbFinancial.getBuyMoney());

        BigDecimal result = resultIncome.divide((new BigDecimal(tbFinancial.getKeepDays())),2,BigDecimal.ROUND_HALF_UP);

        hashMap.put("result", "本金:" + Num2CnUtil.bigDecimalToString(tbFinancial.getBuyMoney())
                + ",持有天数:" + tbFinancial.getKeepDays()
                + "天,总利息:" + resultIncome
                + "元,平均每天收入:" + result + "元,年收入:" + (result.multiply(new BigDecimal(365))));
        return StringUtils.getJSONString(hashMap);
    }

    @Override
    public FinancialDetailVo getVo(Long id) {
        TbFinancial financial = financialMapper.selectById(id);
        FinancialDetailVo vo = new FinancialDetailVo();
        BeanUtils.copyProperties(financial,vo);
        return vo;
    }

    @Override
    public String delete(Long id) {
        financialMapper.deleteById(id);
        Map<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("result", "删除成功");
        return StringUtils.getJSONString(hashMap);
    }

    public static void main(String[] args) throws Exception{
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
        /*天数差*/
        Date fromDate1 = simpleFormat.parse("2018-03-01");
        Date toDate1 = simpleFormat.parse("2018-03-12");
        long from1 = fromDate1.getTime();
        long to1 = toDate1.getTime();
        int days = (int) ((to1 - from1) / (1000 * 60 * 60 * 24));
        System.out.println("两个时间之间的天数差为：" + days);
        BigDecimal a=new BigDecimal("10");

        BigDecimal b = new BigDecimal("3");

        BigDecimal c = a.divide(b,2, BigDecimal.ROUND_HALF_UP);

        System.out.println(c.multiply(HUNDRED));

    }
}
